package com.bumptech.glide.load.resource.transcode;

import ohos.media.image.PixelMap;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.resource.bytes.BytesResource;
import java.io.ByteArrayOutputStream;
import ohos.media.image.ImagePacker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * An {@link ResourceTranscoder} that converts
 * Bitmaps into byte arrays using Bitmap#compress
 * Bitmap.CompressFormat, int, java.io.OutputStream)}.
 */
public class BitmapBytesTranscoder implements ResourceTranscoder<PixelMap, byte[]> {
  private final String compressFormat;
  private final int quality;

  public BitmapBytesTranscoder() {
    this("image/jpeg", 100);
  }

  // Public API.
  @SuppressWarnings("WeakerAccess")
  public BitmapBytesTranscoder(@NotNull String compressFormat, int quality) {
    this.compressFormat = compressFormat;
    this.quality = quality;
  }

  
  @Nullable
  @Override
  public Resource<byte[]> transcode(
      @NotNull Resource<PixelMap> toTranscode, @NotNull Options options) {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImagePacker imagePacker = ImagePacker.create();
    ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
    packingOptions.format = compressFormat;
    packingOptions.quality = quality;
    packingOptions.numberHint = 1;
    boolean result = imagePacker.initializePacking(os, packingOptions);
    imagePacker.addImage(toTranscode.get());
    imagePacker.finalizePacking();
    imagePacker.release();        
    toTranscode.recycle();
    
    return new BytesResource(os.toByteArray());
  }
}
